{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8f1994a8",
   "metadata": {},
   "source": [
    "# 自定义损失函数\n",
    "自定义损失函数时，我们同样需要继承一个类，可以是`nn.Cell`也可以是`nn.LossBase`。`nn.LossBase`在`nn.Cell`的基础上提供了`get_loss`方法，可以直接获得Loss。\n",
    "\n",
    "下面我们以MAE（Mean Absolute Error）平均绝对误差损失函数为例定义损失函数：\n",
    "\n",
    "$$ loss= \\frac{1}{m}\\sum_{i=1}^m\\lvert y_i-f(x_i) \\rvert $$\n",
    "\n",
    "mindspore的`ops`模块中提供了大量的算子，比如逐元素计算输入Tensor的绝对值的`Abs`算子。\n",
    "我们依旧是重写`__init__`方法和`construct`方法，在`__init__`方法中定义需要使用到的算子，在`construct`方法中构造损失函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "62d9c822",
   "metadata": {},
   "outputs": [],
   "source": [
    "import mindspore.nn as nn\n",
    "import mindspore.ops as ops\n",
    "\n",
    "class MyLossFunction(nn.LossBase):\n",
    "    \"\"\"定义损失函数\"\"\"\n",
    "    def __init__(self):\n",
    "        super(MyLossFunction, self).__init__()\n",
    "        self.abs = ops.Abs()\n",
    "        \n",
    "    def construct(self, target, predict):\n",
    "        x = self.abs(target - predict)\n",
    "        return self.get_loss(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d626c61",
   "metadata": {},
   "source": [
    "`get_loss`方法位于`mindspore.nn.LossBase`中，其可以返回加权后的损失值，具体可以查看官方文档。\n",
    "\n",
    "我们可以体验一下这个损失函数:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7c323a91",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.0\n"
     ]
    }
   ],
   "source": [
    "import mindspore as ms\n",
    "import numpy as np\n",
    "\n",
    "lossfunction = MyLossFunction()\n",
    "x = ms.Tensor(np.array([1, 2, 3]), ms.float32)\n",
    "y = ms.Tensor(np.array([2, 3, 4]), ms.float32)\n",
    "output = lossfunction(x, y)\n",
    "print(output)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "mindspore",
   "language": "python",
   "name": "mindvision"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
